import React, { useState } from 'react';
import styles from './index.less';
import { Input, Form, Button, Upload, Spin } from 'antd';
import { connect } from 'dva';
// components
import { TRMessage } from '@/components';
import { default as MobileAlertModal } from './modal';
// utils
import { GetFileBase64 } from '@/utils/utils';
import { emailReg, phoneReg } from '@/utils/regExp';
import { updatePersonInfo } from '@/services/user';
import { AlertResult, HttpCode } from '@/utils/contacts';

const imgFormat = ['image/gif', 'image/jpeg', 'image/jpg', 'image/png'];
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};

const getFormList = (data) => {
  return [
    {
      label: '姓名',
      key: 'name',
      maxLength: 10,
      initialValue: data.name,
      rules: [{ required: true, message: '姓名不能为空' }],
    },
    {
      label: '手机号',
      key: 'mobile',
      initialValue: data.mobile,
      rules: [
        { pattern: phoneReg, message: '请录入正确的手机号码' },
        { required: true, message: '手机号不能为空' },
      ],
    },
    {
      label: '邮箱',
      key: 'email',
      initialValue: data.email || '',
      rules: [{ pattern: emailReg, message: '请录入正确的邮箱' }],
    },
  ];
};

const PersonalMessageComp = (props) => {
  const personalForm = React.createRef();

  const { currentUser, dispatch } = props;
  const formList = getFormList(currentUser);

  const [file, setFile] = useState(null);
  const [imgUrl, setImgUrl] = useState(currentUser.avatar);
  const [loading, setLoading] = useState(false);
  const [imgLastName, setImgLastName] = useState('');

  // eslint-disable-next-line no-shadow
  const upLoadChange = async ({ file, fileList }) => {
    const fileName = file.name.split('.');
    setImgLastName(fileName[fileName.length - 1].toLowerCase());
    const imageUrl = await GetFileBase64(fileList[0].originFileObj);
    setFile(file);
    setImgUrl(imageUrl);
  };
  const handleSubmit = () => {
    if (imgFormat.indexOf(`image/${imgLastName}`) === -1 && file) {
      TRMessage.error('上传图片仅支持gif、jpeg、jpg、png格式');
      return;
    }
    personalForm &&
      personalForm.current.validateFields().then(async (values) => {
        const params = new FormData();
        if (file) {
          params.append('file', file);
        }
        params.append('personId', currentUser.personId);
        params.append('name', values.name);
        params.append('mobile', values.mobile);
        params.append('email', values.email);

        let changeMobile = false;
        if (values.mobile !== currentUser.mobile) {
          const obj = await MobileAlertModal.show();
          if (obj.index === AlertResult.SUCCESS) {
            changeMobile = true;
            params.append('password', obj.inputValue);
          } else {
            return;
          }
        }
        personInfo(params, changeMobile);
      });
  };
  const personInfo = async (params, changeMobile) => {
    setLoading(true);
    const res = await updatePersonInfo(params);
    setLoading(false);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('修改成功！');
      if (changeMobile) {
        dispatch({ type: 'login/logout' });
      } else {
        dispatch({ type: 'user/fetchCurrent' });
      }
    } else {
      TRMessage.error(res.message);
    }
  };
  return (
    <Spin spinning={loading}>
      <div className={styles.personalMessageBox}>
        <div className={styles.header}>
          <div className={styles.title}>个人信息</div>
        </div>
        <div className={styles.headImg}>
          <Upload
            accept={imgFormat.join(',')}
            beforeUpload={() => {
              return false;
            }}
            fileList={[]}
            showUploadList={false}
            onChange={upLoadChange}
          >
            <img src={imgUrl} alt="" />
            <div className={styles.info}>
              <span className={styles.actions}>更换头像</span>
            </div>
          </Upload>
        </div>
        <Form {...formItemLayout} ref={personalForm} className={styles.from}>
          {formList.map((item, index) => {
            return (
              <Form.Item
                name={item.key}
                label={item.label}
                key={index}
                rules={item.rules || []}
                validateTrigger={'onBlur'}
                initialValue={item.initialValue}
              >
                <Input maxLength={item.maxLength} />
              </Form.Item>
            );
          })}
        </Form>
        <Button type="primary" onClick={handleSubmit} className={styles.submitBtn}>
          提交
        </Button>
      </div>
    </Spin>
  );
};

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(PersonalMessageComp);
